package com.pat.manager;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.pat.om.MobilePhone;
import com.pat.utils.HibernateUtil;

public class MobilePhoneManager {

	public List get() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.getTransaction().begin();
		List result = session.createCriteria(MobilePhone.class).list();
		session.getTransaction().commit();

		return result;
	}

	public List get(String number) {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.getTransaction().begin();

		String hql = "FROM MobilePhone a WHERE a.number = :cell_number";
		Query query = session.createQuery(hql);
		query.setParameter("cell_number", number);
		List results = query.list();

		session.getTransaction().commit();

		return results;
	}

	public void add(String number, String name, String gcmRegistration, String mobilephoneTypeId) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.getTransaction().begin();

		MobilePhone mobilePhone = new MobilePhone();
		mobilePhone.setNumber(number);
		mobilePhone.setName(name);
		mobilePhone.setGcmRegistration(gcmRegistration);
		mobilePhone.setMobilephoneType_id(mobilephoneTypeId);
		
		session.delete(mobilePhone);
		session.save(mobilePhone);

		session.getTransaction().commit();
	}

	public int delete(String number) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.getTransaction().begin();

		String hql = "delete from MobilePhone a where a.number = :cell_number";
		Query query = session.createQuery(hql);
		query.setParameter("cell_number", number);
		int rowCount = query.executeUpdate();
		session.getTransaction().commit();
		return rowCount;

	}

	public void delete(MobilePhone mobilePhone) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.getTransaction().begin();
		session.delete(mobilePhone);
		session.getTransaction().commit();
	}

	public void update(MobilePhone mobilePhone) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.getTransaction().begin();
		session.update(mobilePhone);
		session.getTransaction().commit();

	}

	public void add(MobilePhone mobilePhone) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.getTransaction().begin();
		session.delete(mobilePhone);
		session.save(mobilePhone);
		session.getTransaction().commit();

	}

}
